#include <stdio.h>

const int BUFFER_SIZE=1024;
const int MAX_INT=1024;

void* compare(void* a,void* b){
	return *(int*)a - *(int*)b;
}

int getnext(FILE* fp){
	int st=0;
	char buffer[32];
	int count=0;
	char ch;
	while( (ch=getc(fp))!=EOF ){
		if(count==0 && (ch==' ' || ch=='\t')){
			continue;
		}else if(count>0 && (ch==' ' || ch=='\t')){
			buffer[count]='\0';
			return atoi(buffer);
		}
		buffer[count]=ch;
		count++;
	}
	return -1;
}

char* mergefile(char* file1,char* file2){
	char *filename=malloc(256);
	memset(filename,'\0',256);
	strcat(filename,file1);
	strcat(filename,file2);
	
	FILE* fp1=fopen(file1,"r");
	FILE* fp2=fopen(file2,"r");
	printf("file name:%s\n",filename);
	FILE* fp=fopen(filename,"w+");
	
	int a=getnext(fp1);
	int b=getnext(fp2);
	int ca=0;
	int cb=0;
	while(! (a<0 && b<0)){		
	//	printf("%d,%d\n",a,b);
		if(a<0){
			fprintf(fp,"%d ",b);
			b=getnext(fp2);
			cb++;
		}else if(b<0){
			fprintf(fp,"%d ",a);
			a=getnext(fp2);
			ca++;
		}else{
			if(a<b){
				fprintf(fp,"%d ",a);
				a=getnext(fp1);
				ca++;
			}else{
				fprintf(fp,"%d ",b);
				b=getnext(fp2);
				cb++;
			}
		}
	}
	fclose(fp1);
	fclose(fp2);
	fclose(fp);
	//printf("a:%d b:%d\n",ca,cb);
	return filename;
}

int main(){
	int data[MAX_INT];
	char *files[]={"data1","data2","data3"};
	char buffer[256];
	
	int fc=0;
	for(;fc<3;fc++){
		FILE* f=fopen(files[fc],"r");
		char* buffer=(char*)malloc(20);
		int count=0;
		char ch;
		int i=0;
		while( (ch=getc(f)) !=EOF){
			if(ch==' ' || ch=='\t' || ch=='\n'){
				buffer[i+1]='\0';
				data[count]=atoi(buffer);
				count++;
				i=0;
			}else{
				buffer[i]=ch;
				i++;
			}
		}
		fclose(f);
		
		qsort(data,count,sizeof(int),compare);
		memset(buffer,'\0',256);
		buffer[0]='\0';
		buffer=strcat(buffer,files[fc]);
		buffer=strcat(buffer,"_sorted");
		FILE* fp=fopen(buffer,"w+");
		for(i=0;i<count;i++){			
			fprintf(fp,"%d\t",data[i]);
		}
		fclose(fp);		
	}
	//3files merge 1,2 then merge 1,2 3
	char* mf=mergefile("data1_sorted","data2_sorted");
	mergefile(mf,"data3_sorted");
}
